import { useState, useEffect, FC, SyntheticEvent, ChangeEvent } from 'react'
import { Scrollbars } from 'react-custom-scrollbars'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import { BaseOptionType, DefaultOptionType } from 'antd/lib/select'
import { IData, IResponseCodeType, PagingSize, IDepartmentAdminListModel, IRoleAdminListModel, IDepartmentAdminInfo, IMemberAdminListModel, IMemberAdminInfo, IMemberAdminAddInfo, IAllDepartmentListModel } from '@/models/common'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import util from '@/utils/util'
import { useAppDispatch, useAppSelector } from '@/store'
import { ApartmentOutlinedIcon, EditOutlinedIcon, DeleteOutlinedIcon, DownOutlinedIcon, UserAddOutlinedIcon } from '@/models/icons'
import * as api from '@/api'
import { Avatar, Layout, Row, Tree, Col, Modal, Space, Table, Card, Form, Input, Select, TreeSelect } from 'antd'
import './memberadmin.scss'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  selectedKeys: React.Key[]
  selectedDepartment: IDepartmentAdminInfo
  departmentTreeData: IDepartmentAdminInfo[]
  departmentUpdateModalOpen: boolean,
  departmentUpdateRow: ColumnsDataType

  memberUpdateModalOpen: boolean
  /**
   * 当前修改行信息
   */
  memberUpdateRow: IMemberAdminInfo
  pageLoading: boolean
  /**
   * 表格数据
   */
  memberTableList: ColumnsDataType[]
  /**
  * 当前页码
  */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean

  roleOptions: BaseOptionType[]
  sexOptions: DefaultOptionType[]
  typeOptions: DefaultOptionType[]
  userStateOptions: DefaultOptionType[]
  notAuth: boolean
}
const Index: FC = () => {
  const userInfo = useAppSelector((state) => state.login.userInfo)
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      selectedKeys: [],
      selectedDepartment: {},
      departmentTreeData: [],
      departmentUpdateModalOpen: false,
      departmentUpdateRow: {
        id: "",
        name: "",
        code: "",
        child_code: "",
        parent_code: "",
        parent_id: ""
      },

      memberUpdateModalOpen: false,
      memberUpdateRow: {
        user_id: "",
        name: "",
        phone: "",
        role_ids: [],
        email: "",
        type: "0",
        sex: "1",
        user_state: "0",
        department_id: ""
      },
      pageLoading: false,
      memberTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,

      roleOptions: [],
      sexOptions: [
        { label: "保密", value: "0" },
        { label: "男", value: "1" },
        { label: "女", value: "2" },
      ],
      typeOptions: [
        { label: "普通人员", value: "0" },
        { label: "后台管理员", value: "-1" },
        { label: "平台超级管理员", value: "1" },
      ],
      userStateOptions: [
        { label: "正常", value: "0" },
        { label: "锁定", value: "1" },
        { label: "冻结", value: "2" },
        { label: "注销", value: "3" },
      ],
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])


  const events = {
    //部门选中
    onDepartmentSelect(selectedKeys: React.Key[], info: any) {
      // console.log('selectedKeys:', selectedKeys, info);
      const { ViewModel } = data
      ViewModel.selectedKeys = selectedKeys
      ViewModel.selectedDepartment = selectedKeys.length == 0 ? {} : info.node
      ViewModel.page = 1
      setData({ ...data })
      methods.requestMemberList()
    },
    //部门新增
    onClickAddDepartment() {
      const { ViewModel } = data
      let record = {
        id: "",
        name: "",
        code: "",
        child_code: "",
        parent_code: "",
        parent_id: ""
      }
      if (ViewModel.selectedKeys.length > 0) {
        record.parent_code = ViewModel.selectedDepartment.code!
      }
      events.resetDepartmentUpdateRow(true, record)
    },
    //部门编辑
    onClickEditDepartment(e: SyntheticEvent, record: IDepartmentAdminInfo) {
      util.cancelBubble(e)
      events.resetDepartmentUpdateRow(true, record)
    },
    //部门删除
    onClickDeleteDepartment(e: SyntheticEvent, record: IDepartmentAdminInfo) {
      util.cancelBubble(e)
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该部门吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteDepartment(record.id as string)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateDepartmentNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.departmentUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onUpdateDepartmentChildCodeChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.departmentUpdateRow.child_code = e.target.value
      ViewModel.departmentUpdateRow.code = ViewModel.departmentUpdateRow.parent_code + e.target.value
      setData({ ...data })
    },
    onDepartmentUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.departmentUpdateRow.child_code) {
        util.alertTip('请输入子编码')
        return
      }
      if (!ViewModel.departmentUpdateRow.name) {
        util.alertTip('请输入部门名称')
        return
      }
      if (ViewModel.departmentUpdateRow.id) {
        methods.requestUpdateDepartment()
      } else {
        methods.requestAddDepartment()
      }
    },
    onDepartmentUpdateRowCancel() {
      events.resetDepartmentUpdateRow(false)
    },
    resetDepartmentUpdateRow(departmentUpdateModalOpen: boolean, record?: IDepartmentAdminInfo) {
      const { ViewModel } = data
      ViewModel.departmentUpdateRow.name = record ? record.name! : ''
      ViewModel.departmentUpdateRow.id = record ? record.id! : ''
      ViewModel.departmentUpdateRow.code = record ? record.code! : ''
      ViewModel.departmentUpdateRow.parent_code = record ? record.parent_code! : ''
      ViewModel.departmentUpdateRow.child_code = record ? record.child_code! : ''
      ViewModel.departmentUpdateRow.parent_id = record ? record.parent_id! : ''
      ViewModel.departmentUpdateModalOpen = departmentUpdateModalOpen
      setData({ ...data })
    },
    onClickResetDepartmentChecked() {
      const { ViewModel } = data
      ViewModel.selectedKeys = []
      setData({ ...data })
    },


    //成员新增
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.name = ''
      ViewModel.memberUpdateRow.user_id = ''
      ViewModel.memberUpdateRow.phone = ''
      ViewModel.memberUpdateRow.email = ''
      ViewModel.memberUpdateRow.sex = '1'
      ViewModel.memberUpdateRow.role_ids = []
      ViewModel.memberUpdateRow.type = '0'
      ViewModel.memberUpdateRow.user_state = '0'
      ViewModel.memberUpdateRow.department_id = ViewModel.selectedKeys[0] as string
      ViewModel.memberUpdateModalOpen = true
      setData({ ...data })
    },
    //成员编辑
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.name = record.name
      ViewModel.memberUpdateRow.user_id = record.user_id
      ViewModel.memberUpdateRow.phone = record.phone
      ViewModel.memberUpdateRow.email = record.email
      ViewModel.memberUpdateRow.sex = record.sex
      ViewModel.memberUpdateRow.role_ids = record.role_ids as any
      ViewModel.memberUpdateRow.type = record.user_type
      ViewModel.memberUpdateRow.user_state = record.user_state
      ViewModel.memberUpdateRow.department_id = record.department_id
      ViewModel.memberUpdateModalOpen = true
      setData({ ...data })
    },
    //成员重置密码
    onClickResetPwdRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '重置密码',
        centered: true,
        closable: true,
        content: '确认重置该成员密码吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestResetMemberPwd(record.user_id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    //成员删除
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该成员吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteMember(record.user_id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateMemberNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onUpdateMemberPhoneChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.phone = e.target.value
      setData({ ...data })
    },
    onUpdateMemberSexChange(value: string) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.sex = value
      setData({ ...data })
    },
    onUpdateMemberStatusChange(value: string) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.user_state = value
      setData({ ...data })
    },
    onUpdateMemberDepartmentChange(newValue: string) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.department_id = newValue
      setData({ ...data })
    },
    onUpdateMemberTypeChange(value: string) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.type = value
      setData({ ...data })
    },
    onUpdateMemberEmailChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.email = e.target.value
      setData({ ...data })
    },
    onMemberUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.memberUpdateRow.name) {
        util.alertTip('请输入成员姓名')
        return
      }
      if (!ViewModel.memberUpdateRow.phone) {
        util.alertTip('请输入手机号')
        return
      }
      const phone_reg = util.getPhoneReg()
      if (!phone_reg.test(ViewModel.memberUpdateRow.phone)) {
        util.alertTip('请输入格式正确的手机号')
        return
      }
      if (!ViewModel.memberUpdateRow.type) {
        util.alertTip('请选择用户类型')
        return
      }
      if (!ViewModel.memberUpdateRow.sex) {
        util.alertTip('请选择性别')
        return
      }
      if (!ViewModel.memberUpdateRow.department_id) {
        util.alertTip('请选择所属部门')
        return
      }
      if (ViewModel.memberUpdateRow.user_id) {
        methods.requestUpdateMember()
      } else {
        methods.requestAddMember()
      }
    },
    onMemberUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.memberUpdateModalOpen = false
      setData({ ...data })
    },
    //角色改变
    onRoleChange(value: string[]) {
      const { ViewModel } = data
      ViewModel.memberUpdateRow.role_ids = value
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        ViewModel.page = ViewModel.page + 1
        ViewModel.pageLoading = true
        setData({ ...data })
        methods.requestMemberList()
      }
    },
  }
  const methods = {
    /**
     * 加载角色
     */
    async requestRoleList() {
      const { ViewModel } = data
      let res = await api.common.getRoleAdminList<IRoleAdminListModel>(null)
      const { code, data: roleAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { result_list = [] } = roleAdminData
        ViewModel.roleOptions = [...result_list]
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 加载全部部门
     */
    async requestAllDepartmentAdminList() {
      const { ViewModel } = data
      let res = await api.common.getAllDepartmentAdminList<IAllDepartmentListModel>(null)
      let { code, message, data: departmentAdminData, } = res
      if (code == IResponseCodeType.Success) {
        let { result_list = [] } = departmentAdminData
        ViewModel.departmentTreeData = [...result_list]
        setData({ ...data })
        methods.requestRoleList()
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除部门
     * @param id 
     */
    async requestDeleteDepartment(id: string) {
      let res = await api.common.deleteDepartmentAdmin<null>({
        id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        const { ViewModel } = data
        const { departmentTreeData } = ViewModel
        util.removeNodeInTree(departmentTreeData, id)
        ViewModel.selectedKeys = []
        ViewModel.departmentTreeData = [...departmentTreeData]
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 新增部门
     */
    async requestAddDepartment() {
      const { ViewModel } = data
      const parent_id = ViewModel.selectedKeys.length == 0 ? '' : ViewModel.selectedKeys[0] as string
      let res = await api.common.addDepartmentAdmin({
        name: ViewModel.departmentUpdateRow.name,
        child_code: ViewModel.departmentUpdateRow.child_code,
        parent_id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.departmentUpdateModalOpen = false
        setData({ ...data })
        methods.requestAllDepartmentAdminList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 编辑部门
     */
    async requestUpdateDepartment() {
      const { ViewModel } = data
      let res = await api.common.editDepartmentAdminInfo({
        name: ViewModel.departmentUpdateRow.name,
        id: ViewModel.departmentUpdateRow.id,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        const { departmentTreeData } = ViewModel
        util.departmentForEach(departmentTreeData, (department) => {
          if (department.id == ViewModel.departmentUpdateRow.id) {
            department.name = ViewModel.departmentUpdateRow.name
          }
        })
        ViewModel.departmentTreeData = [...departmentTreeData]
        ViewModel.departmentUpdateModalOpen = false
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },

    /**
     * 加载成员
     */
    async requestMemberList() {
      const { ViewModel } = data
      let { memberTableList, page, pageSize, selectedKeys } = ViewModel
      if (selectedKeys.length == 0) {
        return
      }
      let res = await api.common.getMemberAdminList<IMemberAdminListModel>({
        department_id: selectedKeys[0] as string,
        page: page,
        limit: pageSize
      })
      const { code, data: memberAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { result_list = [] } = memberAdminData
        if (page == 1) {
          memberTableList = []
        }
        ViewModel.memberTableList = [...memberTableList, ...result_list]
        if (result_list.length < pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = true
        }
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 新增成员
     */
    async requestAddMember() {
      const { ViewModel } = data
      let res = await api.common.addMemberAdmin<IMemberAdminAddInfo>({
        name: ViewModel.memberUpdateRow.name,
        phone: ViewModel.memberUpdateRow.phone,
        email: ViewModel.memberUpdateRow.email,
        sex: ViewModel.memberUpdateRow.sex,
        type: ViewModel.memberUpdateRow.type,
        role_ids: JSON.stringify(ViewModel.memberUpdateRow.role_ids) as any,
        department_id: ViewModel.memberUpdateRow.department_id,
        user_state: ViewModel.memberUpdateRow.user_state,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.memberUpdateModalOpen = false
        ViewModel.page = 1
        setData({ ...data })
        methods.requestMemberList()
        methods.requestAllDepartmentAdminList()
        Modal.success({
          content: res.data.password,
          centered: true,
        });
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 更新成员
     */
    async requestUpdateMember() {
      const { ViewModel } = data
      const oldMember = ViewModel.memberTableList.find(o => o.user_id == ViewModel.memberUpdateRow.user_id)
      let isChange = oldMember && oldMember.department_id != ViewModel.memberUpdateRow.department_id
      let res = await api.common.editMemberAdmin({
        user_id: ViewModel.memberUpdateRow.user_id,
        name: ViewModel.memberUpdateRow.name,
        phone: ViewModel.memberUpdateRow.phone,
        email: ViewModel.memberUpdateRow.email,
        sex: ViewModel.memberUpdateRow.sex,
        type: ViewModel.memberUpdateRow.type,
        role_ids: JSON.stringify(ViewModel.memberUpdateRow.role_ids) as any,
        department_id: ViewModel.memberUpdateRow.department_id,
        user_state: ViewModel.memberUpdateRow.user_state,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.memberUpdateModalOpen = false
        ViewModel.page = 1
        setData({ ...data })
        methods.requestMemberList()
        if (isChange) {
          methods.requestAllDepartmentAdminList()
        }
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除成员
     * @param user_id 
     */
    async requestDeleteMember(user_id: string) {
      let res = await api.common.deleteMemberAdmin<null>({
        user_id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        data.ViewModel.page = 1
        methods.requestMemberList()
        methods.requestAllDepartmentAdminList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 成员重置密码
     * @param user_id 
     */
    async requestResetMemberPwd(user_id: string) {
      let res = await api.common.resetMemberAdminPwd<IMemberAdminAddInfo>({
        user_id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        Modal.success({
          content: res.data.password,
          centered: true,
        });
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '姓名',
          align: "left",
          key: 'name',
          dataIndex: 'name',
          width: 150,
        },
        {
          title: '手机号',
          align: "left",
          key: 'phone',
          dataIndex: 'phone',
          width: 150,
        },
        {
          title: '角色',
          align: "left",
          key: 'role_names',
          dataIndex: 'role_names',
          width: 150,
        },
        {
          title: '类型',
          align: "left",
          key: 'user_type_value',
          dataIndex: 'user_type_value',
          width: 150,
        },
        {
          title: '部门',
          align: "left",
          key: 'department_name',
          dataIndex: 'department_name',
          width: 150,
        },
        {
          title: '性别',
          align: "left",
          key: 'sex_value',
          dataIndex: 'sex_value',
          width: 60,
        },
        {
          title: '状态',
          align: "left",
          key: 'user_state_value',
          dataIndex: 'user_state_value',
          width: 60,
        },
        {
          title: '邮箱',
          align: "left",
          key: 'email',
          dataIndex: 'email',
          width: 150,
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          fixed: "right",
          width: 200,
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickResetPwdRow(_, record, index)}>
                重置密码
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                修改
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                删除
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <Layout className='memberadmin-body'>
        <Layout.Sider theme='light' className='memberadmin-sider' width={300}>
          <Scrollbars autoHide>
            <Row className='add-department-wrap' align='middle'>
              <XlButtonFC type='primary' icon={<ApartmentOutlinedIcon />} onClick={events.onClickAddDepartment}>添加子部门</XlButtonFC>
            </Row>
            <Row align='middle' className='company-name-warp' onClick={events.onClickResetDepartmentChecked}>
              <Col><Avatar size={24} src={userInfo.tenant_logo}></Avatar></Col>
              <Col className='name'>
                <Col>{userInfo.tenant_name}</Col>
              </Col>
              {/* <Col>(425人)</Col> */}
            </Row>
            <Col className='department-tree-wrap'>
              <Tree
                autoExpandParent
                blockNode
                onSelect={events.onDepartmentSelect}
                treeData={data.ViewModel.departmentTreeData}
                selectedKeys={data.ViewModel.selectedKeys}
                fieldNames={{
                  title: "name",
                  key: "id",
                }}
                titleRender={
                  (nodeData) => {
                    return <Row justify='space-between' align='middle' className='title-render-wrap'>
                      <Col className='title'>{nodeData.name} {nodeData.count && parseFloat(nodeData.count) > 0 ? `(${nodeData.count}人)` : ''}</Col>
                      <Row align='middle' gutter={8} className='title-action-wrap'>
                        <Col title='编辑' onClick={(e) => { events.onClickEditDepartment(e, nodeData) }}><EditOutlinedIcon /></Col>
                        <Col title='删除' onClick={(e) => { events.onClickDeleteDepartment(e, nodeData) }}><DeleteOutlinedIcon /></Col>
                      </Row>
                    </Row>
                  }
                }
              />
            </Col>
          </Scrollbars>
        </Layout.Sider>
        <Layout.Content className='memberadmin-content'>
          <Card
            title={<strong>{data.ViewModel.selectedDepartment.name}</strong>}
            style={{ display: data.ViewModel.selectedKeys?.length == 0 ? 'none' : 'block' }}
          >
            <Col className='member-list-wrap'>
              {/* 按钮操作区域 */}
              <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
                <Col>
                  <Space size={6}>
                    <XlButtonFC type='primary' onClick={events.onClickAddRow} icon={<UserAddOutlinedIcon />}>添加成员</XlButtonFC>
                  </Space>
                </Col>
                <Col className='count'>
                  {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.memberTableList.length}个
                </Col>
              </Row>
              {/* 表格区域 */}
              <Row className='tableWrap'>
                <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                  <Table
                    scroll={{
                      x: '100%',
                      y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                    }}
                    loading={data.ViewModel.pageLoading}
                    tableLayout='fixed'
                    rowKey='user_id'
                    pagination={false}
                    columns={methods.createColumns()}
                    dataSource={data.ViewModel.memberTableList}
                  />
                </Col>

                {
                  data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                    <Col>点击加载更多</Col>
                    <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                  </Row> : null
                }
              </Row>
            </Col>
          </Card>
          {/* 添加/修改部门弹出框 */}
          <XlModalFC
            open={data.ViewModel.departmentUpdateModalOpen}
            onOk={events.onDepartmentUpdateRowOk}
            onCancel={events.onDepartmentUpdateRowCancel}
            title='新增/修改部门'
            destroyOnClose
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              autoComplete="off"
            >
              <Form.Item
                label="上级编码"
              >
                <Input disabled value={data.ViewModel.departmentUpdateRow.parent_code || '-'} />
              </Form.Item>
              <Form.Item
                label="编码"
              >
                <Input disabled value={data.ViewModel.departmentUpdateRow.code || '-'} />
              </Form.Item>
              <Form.Item
                label="子编码"
                required
              >
                <Input maxLength={2} disabled={data.ViewModel.departmentUpdateRow.id.length > 0} value={data.ViewModel.departmentUpdateRow.child_code} onChange={events.onUpdateDepartmentChildCodeChange} placeholder='请输入部门子编码(两位数字)' />
              </Form.Item>
              <Form.Item
                label="部门名称"
                required
              >
                <Input value={data.ViewModel.departmentUpdateRow.name} onChange={events.onUpdateDepartmentNameChange} allowClear placeholder='请输入部门名称' />
              </Form.Item>
            </Form>
          </XlModalFC>
          {/* 添加/修改成员弹出框 */}
          <XlModalFC
            open={data.ViewModel.memberUpdateModalOpen}
            onOk={events.onMemberUpdateRowOk}
            onCancel={events.onMemberUpdateRowCancel}
            title='新增/修改成员'
            destroyOnClose
          >
            <Form
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 18 }}
              autoComplete="off"
            >
              <Form.Item
                label="姓名"
                required
              >
                <Input value={data.ViewModel.memberUpdateRow.name} onChange={events.onUpdateMemberNameChange} allowClear placeholder='请输入成员姓名' />
              </Form.Item>
              <Form.Item
                label="手机"
                required
              >
                <Input type='text' value={data.ViewModel.memberUpdateRow.phone} maxLength={11} onChange={events.onUpdateMemberPhoneChange} placeholder='请输入手机号' allowClear />
              </Form.Item>
              <Form.Item
                label="类型"
                required
              >
                <Select
                  value={data.ViewModel.memberUpdateRow.type}
                  placeholder='请选择用户类型'
                  allowClear
                  style={{ width: '100%' }}
                  onChange={events.onUpdateMemberTypeChange}
                  options={data.ViewModel.typeOptions}
                />
              </Form.Item>
              <Form.Item
                label="性别"
                required
              >
                <Select
                  placeholder='请选择性别'
                  allowClear
                  value={data.ViewModel.memberUpdateRow.sex}
                  style={{ width: '100%' }}
                  onChange={events.onUpdateMemberSexChange}
                  options={data.ViewModel.sexOptions}
                />
              </Form.Item>
              <Form.Item
                label="部门"
                required
              >
                <TreeSelect
                  placeholder='请选择所属部门'
                  allowClear
                  showSearch
                  value={data.ViewModel.memberUpdateRow.department_id || undefined}
                  style={{ width: '100%' }}
                  onChange={events.onUpdateMemberDepartmentChange}
                  treeData={data.ViewModel.departmentTreeData}
                  treeDefaultExpandAll
                  fieldNames={{
                    label: "name",
                    value: "id",
                  }}
                  treeNodeFilterProp='name'
                />
              </Form.Item>
              <Form.Item
                label="角色"
              >
                <Select
                  fieldNames={{
                    label: "name",
                    value: "id",
                  }}
                  showArrow
                  style={{ width: '100%' }}
                  maxTagCount='responsive'
                  mode="multiple"
                  options={data.ViewModel.roleOptions}
                  placeholder='请选择角色'
                  allowClear
                  value={data.ViewModel.memberUpdateRow.role_ids}
                  onChange={events.onRoleChange}
                  filterOption={(input, option) =>
                    ((option?.name ?? '') as string).toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
              <Form.Item
                label="状态"
              >
                <Select
                  placeholder='请选择用户状态'
                  allowClear
                  value={data.ViewModel.memberUpdateRow.user_state}
                  style={{ width: '100%' }}
                  onChange={events.onUpdateMemberStatusChange}
                  options={data.ViewModel.userStateOptions}
                />
              </Form.Item>
              <Form.Item
                label="邮箱"
              >
                <Input value={data.ViewModel.memberUpdateRow.email} onChange={events.onUpdateMemberEmailChange} allowClear placeholder='请输入邮箱' />
              </Form.Item>
            </Form>
          </XlModalFC>
        </Layout.Content>
      </Layout>
    }
  }

  return methods.renderPage()
}
export default Index
